import 'dart:convert';
import 'dart:math';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xingsu/net/apis.dart';
import 'package:xingsu/net/http_manager.dart';
import 'package:xingsu/util/use_preferences.dart';

import '../../../widget/guide_dialog.dart';

class PublisherViewModel extends GetxController {
  final recentList = [].obs;
  final activityList = [].obs;
  final recommendList = [].obs;
  final banner1 = {}.obs;
  final banner2 = {}.obs;
  final banner3 = {}.obs;
  int recommendPage = 1;

  List ddlist = [];

  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  @override
  void onInit() {
    super.onInit();

    if (!UserPreferences.getShowPublishGuide()) {
      Future.delayed(const Duration(milliseconds: 100), () {
        showGuideDialog();
        UserPreferences.setShowPublishGuide(true);
      });
    }

    loadData();
  }

  void loadData() {
    recommendPage = 1;
    recommendList.clear();
    _loadRecentList();
    // _loadActivityList();
    _loadRecommendList();
    loadBanner();
  }

  void _loadRecentList() async {
    String jsonData = await rootBundle.loadString('assets/json/recent.json');
    List allList = json.decode(jsonData);

    recentList.assignAll(allList.sublist(0, 10));
  }

  void loadBanner() async {
    String jsonData = await rootBundle.loadString('assets/json/banner.json');
    List allList = json.decode(jsonData);
    banner2.assignAll(allList[1]);
    banner3.assignAll(allList[2]);
    banner1.assignAll(allList[0]);
  }

  void _loadActivityList() {
    HttpManager.getInstance().get(Apis.activityList,
        params: {"limit": 5, "offset": 0, "processing_status_list": "1,2,3"},
        success: (resp) {
      if (refreshController.isRefresh) {
        refreshController.refreshCompleted();
      }
      List list = resp["reward_activity_list"] ?? [];
      activityList.assignAll(list);
    });
  }

  void _loadRecommendList() async {
    if (recommendPage > 10) {
      return;
    }

    refreshController.loadComplete();
    refreshController.refreshCompleted();

    String jsonData = await rootBundle.loadString('assets/json/recommend.json');
    List allList = json.decode(jsonData);

    recommendList.assignAll(allList.sublist(0, recommendPage * 10));
  }

  void loadMore() {
    recommendPage++;
    _loadRecommendList();
  }
}
